<?php

namespace app\admin\controller\course;

use app\common\controller\Backend;
use app\common\model;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教室课表
 *
 * @package app\admin\controller
 */
class Classroom extends Backend
{
    /**
     * @var \app\common\model\CourseDetail
     */
    protected $model = null;
    protected $noNeedRight = ['searchList', 'cxSelect'];
    protected $schoolLimit = true;
    //protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CourseDetail');
    }

    public function index()
    {
        if ($this->request->isAjax()) {

            $school_id = $this->request->request('school_id');
            $class_id = $this->request->request('class_id');
            $semester_id = $this->request->request('semester_id');
            $semester_num = $this->request->request('semester_num');

            //教师任课
            $teaches = model\Teach::alias('teach')
                ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
                ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id')
                ->join('__USER__ user', 'user.id = teacher.user_id')
                ->where('teach.school_id', $school_id)
                ->where('FIND_IN_SET(:class_id,teach.class_ids)', ['class_id' => $class_id])
                ->column('teach.id,subject.name subject_name,user.nickname teacher_name', 'teach.id');

            $num = 1;
            foreach ($teaches as $key => $value) {
                $teaches[$key]['num'] = $num > 8 ? $num % 8 : $num;
                $num++;
            }

            // 课表
            $course_details = [];
            $list = $this->model->where('class_id', $class_id)->where('semester_id', $semester_id)->where('semester_num', $semester_num)->select();
            foreach ($list as $key => $value) {
                if (isset($teaches[$value['teach_id']])) {
                    $value['num'] = $teaches[$value['teach_id']]['num'];
                    $value['subject_name'] = $teaches[$value['teach_id']]['subject_name'];
                    $value['teacher_name'] = $teaches[$value['teach_id']]['teacher_name'];
                    $course_details[$value['number']][$value['day']] = $value;
                }
            }

            //所有课节
            $class_days = [];
            $list = model\ClassDay::where('school_id', $school_id)->select();
            foreach ($list as $key => $class_day) {
                if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                    $temp = $course_details[$class_day['number']][$class_day['day']];
                    $temp['start_time'] = $class_day['start_time_text'];
                    $temp['end_time'] = $class_day['end_time_text'];
                    $class_days[$class_day['number']][] = $temp;
                } else {
                    $class_days[$class_day['number']][] = [
                        'start_time' => $class_day['start_time_text'],
                        'end_time' => $class_day['end_time_text'],
                    ];
                }
            }
            $class_days = array_values($class_days);

            $teaches = array_values($teaches);

            $this->success('', '', compact('teaches', 'class_days'));
        }

        $result = model\School::with('classes')->whereIn('id', $this->auth->getSchoolIds())->select();
        $grades = model\Grade::all();

        $data = [];
        foreach ($result as $key => $value) {
            $data[$value['id']]['id'] = $value['id'];
            $data[$value['id']]['title'] = $value['name'];
            $data[$value['id']]['type'] = 'school';

            $temp_grades = [];
            foreach ($grades as $k => $grade) {
                $temp_grades[$grade['id']]['id'] = $grade['id'];
                $temp_grades[$grade['id']]['title'] = $grade['name'];
                $temp_grades[$grade['id']]['type'] = 'grade';
                foreach ($value['classes'] as $i => $class) {
                    if ($class['grade_id'] == $grade['id']) {
                        $temp_grades[$grade['id']]['children'][] = [
                            'id' => $class['id'],
                            'school_id' => $value['id'],
                            'title' => $class['name'],
                            'type' => 'classes',
                        ];
                    }
                }
            }

            $data[$value['id']]['children'] = array_values($temp_grades);
        }

        $this->assignconfig('admin', ['school' => array_values($data)]);

        return $this->view->fetch();
    }

    public function add()
    {
        $school_id = $this->request->request('school_id', 0);
        $class_id = $this->request->request('class_id', 0);
        $courses = $this->request->request('course/a', 0);
        $semester_id = $this->request->request('semester_id', 0);
        $semester_num = $this->request->request('semester_num', 0);

        if (!$class_id) {
            $this->error('请先选择班级');
        }

        $course_details = [];

        $list = model\CourseDetail::where('class_id', $class_id)
            ->where('semester_id', $semester_id)
            ->where('semester_num', $semester_num)
            ->select();

        foreach ($list as $key => $value) {
            $course_details[$value['number']][$value['day']] = $value;
            if (!isset($courses[$value['number']]) || !isset($courses[$value['number']][$value['day'] - 1])) {
                $courses[$value['number']][$value['day'] - 1] = '';
            }
        }

        $course_data = [];
        $delete_course_details = [];
        foreach ($courses as $key => $value) {
            foreach ($value as $k => $v) {
                if ($v) {
                    if (isset($course_details[$key]) && isset($course_details[$key][$k + 1])) {
                        $course_data[] = [
                            'id' => $course_details[$key][$k + 1]['id'],
                            'teach_id' => $v,
                            'semester_id' => $semester_id,
                            'semester_num' => $semester_num,
                        ];
                    } else {
                        $course_data[] = [
                            'teach_id' => $v,
                            'class_id' => $class_id,
                            'number' => $key,
                            'day' => $k + 1,
                            'semester_id' => $semester_id,
                            'semester_num' => $semester_num,
                        ];
                    }
                } else {
                    if (isset($course_details[$key]) && isset($course_details[$key][$k + 1])) {
                        $delete_course_details[] = $course_details[$key][$k + 1]['id'];
                    }
                }
            }
        }

        Db::startTrans();
        try {

            $this->model->whereIn('id', $delete_course_details)->delete();
            $this->model->saveAll($course_data);

            $client = new Client([
                'base_uri' => config('classc.url'),
                'timeout' => 30,
                'allow_redirects' => true
            ]);
            $response = $client->request('POST', '/api/v1/baseSocketPush', [
                'form_params' => [
                    'class_id' => $class_id,
                    'content' => [
                        'action' => 'refresh',
                        'params' => 'timetable',
                    ],
                ]
            ]);
            $response->getStatusCode();

            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();


    }





}